import { useUserStore } from '@/stores/user';
import  Request  from 'luch-request';

export const baseURL = 'https://consult-api.itheima.net'
const request = new Request({
  baseURL: baseURL,
  custom: {
    loading: true
  }
})

// 接口白名单
const whiteList = ['/code', '/login', '/login/password']

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    if (config.custom?.loading) {
      //mark:true，加载时显示遮罩层
      uni.showLoading({ title: '正在加载...', mask: true })
    }

    const store = useUserStore()
    if (store.token && !whiteList.includes(config.url!)) { 
      config.header!.Authorization = `Bearer ${store.token}`
    }
   
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 配置响应拦截器
request.interceptors.response.use(
  (res) => {
    // 隐藏加载状态提示
    uni.hideLoading()

    // 统一错误处理
    if (res.data.code !== 10000) {
      uni.showToast({
        title: res.data.message,
        icon: 'none'
      })
      return Promise.reject(res.data)
    }
    // 简化数据返回
    return res.data?.data
  },
  (error) => {
    // 隐藏加载状态提示
    uni.hideLoading()

    if (error.data.code === 401) {
      const store = useUserStore()
      store.clearToken()
      uni.redirectTo({
        url: '/pages/login/index',
      })
    }
    return Promise.reject(error)
  }
)

export { request }